package com.jzwl.xydk.manager.skillUser.controller;

import java.util.ArrayList;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jzwl.common.constant.AjaxStatusConstant;
import com.jzwl.common.constant.Constants;
import com.jzwl.common.excel.ReadWriteExcelUtil;
import com.jzwl.common.log.SystemLog;
import com.jzwl.common.page.PageObject;
import com.jzwl.common.upload.FileUploadUtils;
import com.jzwl.common.upload.MultipartUploadSample;
import com.jzwl.system.base.controller.BaseController;
import com.jzwl.xydk.manager.skillUser.service.SkillUserManagerService;
import com.jzwl.xydk.manager.user.userskillinfo.service.UserSkillinfoService;
import com.jzwl.xydk.sendmessage.SendMessage;
import com.jzwl.xydk.wap.skillUser.service.SkillUserService;
@Controller
@RequestMapping("/skillUserManager")
public class SkillUserManager extends BaseController {
	@Autowired
	private SystemLog systemLog;
	@Autowired
	private Constants constants;
	@Autowired
	private SkillUserManagerService skillUserManagerService;
	@Autowired
	private SkillUserService skillUserService;
	@Autowired
	private UserSkillinfoService userSkillinfoService;
	@Autowired
	private SendMessage sendMessage;
	
	private static Logger log = LoggerFactory.getLogger(SkillUserManager.class);
	//技能空间列表
		//技能空间详情
			//技能空间审核
	//技能大类管理
		//技能小类管理
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：技能空间列表
	 * 创建人： ln
	 * 创建时间： 2016年10月13日
	 * 标记：manager
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/skillSpaceList")
	public String skillSpaceList(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		try {
			PageObject po = skillUserManagerService.skillSpaceList(paramsMap);
			model.addAttribute("userName1",paramsMap.get("userName"));
			model.addAttribute("isRecommend",paramsMap.get("isRecommend"));
			model.addAttribute("skillStatus",paramsMap.get("skillStatus"));
			model.addAttribute("auditState",paramsMap.get("auditState"));
			model.addAttribute("po",po);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "manager/skillSpaceUser/skillSpaceList";
	}
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：去修改基本信息
	 * 创建人： ln
	 * 创建时间： 2016年11月2日
	 * 标记：manager
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/toEditBaseInfo")
	public String toEditBaseInfo(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		try {
			Map<String, Object> skillBaseInfo = skillUserManagerService.getSkillBaseInfo(paramsMap);
			model.addAttribute("baseInfo",skillBaseInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "manager/skillSpaceUser/editBaseInfo";
	}
	
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：修改用户基本信息
	 * 创建人： ln
	 * 创建时间： 2016年11月2日
	 * 标记：manager
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/editBaseInfo")
	public String editBaseInfo(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		try {
			boolean flag = skillUserManagerService.editBaseInfo(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/skillUserManager/skillSpaceList.html";
	}
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：根据基础信息获取技能信息列表。(用于修改技能信息)
	 * 创建人： ln
	 * 创建时间： 2016年11月2日
	 * 标记：
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/skillInfoList")
	public String skillInfoList(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		try {
			String basicId  = String.valueOf(paramsMap.get("id"));
			//获取技能信息列表，根据技能
			List<Map<String, Object>> querySkillByUserId = skillUserManagerService.querySkillByUserId(paramsMap);
			model.addAttribute("po",querySkillByUserId);
			model.addAttribute("basicId",basicId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "manager/skillSpaceUser/skillInfoList";
	}
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：去修改技能信息ById
	 * 创建人： ln
	 * 创建时间： 2016年11月3日
	 * 标记：
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/toUpdateSkillInfo")
	public String toUpdateSkillInfo(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		try{
			createParameterMap(request);
			/*String beforUrl = constants.getXiaoka_weixin_staticresource_path();*/
			String basicId = request.getParameter("basicId");
			String id = request.getParameter("id");
			
			List<Map<String, Object>> classF = userSkillinfoService.getClassF();
			List<Map<String, Object>> classS = userSkillinfoService.getClassS();
			List<Map<String, Object>> images = userSkillinfoService.getImages(id);
			
			/*for(int i=0;i<images.size();i++){
				String beforUrl = constants.getXiaoka_weixin_staticresource_path();
				String imgStr = String.valueOf(images.get(i).get("imgURL"));
				images.get(i).put("imgURL",beforUrl+imgStr);
			}*/
			Map<String,Object> objMap = userSkillinfoService.getById(paramsMap);
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
			List<Map<String,Object>> videoList = new ArrayList<Map<String,Object>>();
			if(null!=objMap.get("textUrl")){
				String textUrl = String.valueOf(objMap.get("textUrl"));
				String[] textArr = textUrl.split(",");
				for(int i=0;i<textArr.length;i++){
					Map<String,Object> map = new HashMap<String, Object>();
					map.put("textUrl", textArr[i]);
					list.add(map);
				}
			}
			if(null!=objMap.get("videoUrl")){
				String videoUrl = String.valueOf(objMap.get("videoUrl"));
				String[] videoArr = videoUrl.split(",");
				for(int i=0;i<videoArr.length;i++){
					Map<String,Object> map = new HashMap<String, Object>();
					map.put("videoUrl", videoArr[i]);
					videoList.add(map);
				}
			}
			model.addAttribute("objMap", objMap);
			model.addAttribute("classF", classF);
			model.addAttribute("classS", classS);
			model.addAttribute("images", images);
			model.addAttribute("basicId", basicId);
			model.addAttribute("textList", list);
			model.addAttribute("videoList", videoList);
			/*model.addAttribute("beforUrl", beforUrl);*/
		}catch(Exception e){
			e.printStackTrace();
			model.addAttribute("msg","获取数据失败");
			return "/error";
		}
		return "manager/skillSpaceUser/editSkillInfo";
	}
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：修改技能信息
	 * 创建人： ln
	 * 创建时间： 2016年11月3日
	 * 标记：
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/updateSkill")
	public String updateUserSkillinfo(HttpServletRequest request, HttpServletResponse response,Model model) {
		try{
			createParameterMap(request);
			String[] answerArr = request.getParameterValues("imgUrl");
			//实现图片的更新，先把图片进行删除
			boolean f = userSkillinfoService.deleteImage(paramsMap);
			String id = paramsMap.get("id").toString();
			if(f){
				for(String answer:answerArr){//存储图片
					userSkillinfoService.addImage(answer,id);
				}
			}
			boolean flag = userSkillinfoService.updateUserSkillinfo(paramsMap);
			if(flag){
				model.addAttribute("basicId",paramsMap.get("basicId"));
				return "redirect:/skillUserManager/skillInfoList.html?id="+paramsMap.get("basicId");
			}else{
				model.addAttribute("msg","保存失败");
				return "/error";
			}
		}catch(Exception e){
			e.printStackTrace();
			model.addAttribute("msg","保存失败");
			return "/error";
		}
	}
	//图片上传
	@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
	public @ResponseBody Map uploadImage(@RequestParam("imgs") MultipartFile[] imgs,HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (imgs == null || imgs.length <=0) {
				map.put("ajax_status", AjaxStatusConstant.AJAX_STATUS_FAILURE);
				map.put("msg", "图片不能为空！");
				return map;
			}
			List pics = new ArrayList();
			String imgPath = "";
			String targetPath = "";
			for (MultipartFile img : imgs) {
				
				String filename = URLEncoder.encode(img.getOriginalFilename(), "utf-8");
				DateFormat df =  new SimpleDateFormat("yyyyMMddHHmmssSSS");
				String name = df.format(new Date());
				Random r = new Random();
				for (int i = 0; i < 3; i++) {
					name += r.nextInt(10);
				}
				String savename = name+filename;
				/*boolean b = MultipartUploadSample.uploadOssImg(savename,img);*/
				boolean b = MultipartUploadSample.uploadOssImg(savename,img);
				
				String beforUrl = constants.getXiaoka_bbs_oosGetImg_beforeUrl();
				String picUrl = beforUrl+savename;
				
				
				/*String picUrl = beforUrl+savename;*/
				
				map.put("imgUrl", picUrl);// 相对路径，存数据库的。
				map.put("targetPath", picUrl);// 绝对路径，显示
				map.put("key", savename);// 绝对路径，显示
//				map.put("filename", filename);
				pics.add(net.sf.json.JSONObject.fromObject(map));
			}
			String result = net.sf.json.JSONArray.fromObject(pics).toString();
			map.put("ajax_status", AjaxStatusConstant.AJAX_STATUS_SUCCESS);
			map.put("pics", result);
		} catch (Exception e) {
			map.put("ajax_status", AjaxStatusConstant.AJAX_STATUS_FAILURE);
			map.put("msg", "上传失败！"+e.getMessage());
			e.printStackTrace();
		}
		return map;
	}
	
	
	
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：获取技能分类小类，根据大分类
	 * 创建人： ln
	 * 创建时间： 2016年11月3日
	 * 标记：
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/queryMinCategoryByMaxId")
	public @ResponseBody Map queryMinCategoryByMaxId(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		Map<String,Object> map = new HashMap<String, Object>();
		try {
			String fatId = String.valueOf(paramsMap.get("fatId"));
			List<Map<String, Object>> minCategoryLis = skillUserService.queryMinCategoryByMaxId(fatId);
			map.put("minList", minCategoryLis);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：技能空间详细信息
	 * 创建人： ln
	 * 创建时间： 2016年10月13日
	 * 标记：
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/skillSpaceDetail")
	public String skillSpaceDetail(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		try {
			Map<String,Object> baseInfo = skillUserManagerService.getSkillBaseInfo(paramsMap);
			List<Map<String,Object>> skillInfo = skillUserManagerService.querySkillByUserId(paramsMap);
			String imgIds = "";
			for (int i = 0; i < skillInfo.size(); i++) {
				String id  = String.valueOf(skillInfo.get(i).get("id"));
				imgIds += id+",";
			}
			imgIds = imgIds.substring(0,imgIds.length()-1);
			//获取技能图片
			List<Map<String,Object>> imgList = skillUserManagerService.queryImgBySkillIds(imgIds);
			/*if(imgList.size()>0){
				for(int i =0;i<imgList.size();i++){
					String imgStr = String.valueOf(imgList.get(i).get("imgURL"));
					imgStr = constants.getXiaoka_weixin_staticresource_path()+imgStr;
					imgList.get(i).put("imgURL", imgStr);
				}
			}*/
			model.addAttribute("baseInfo", baseInfo);
			model.addAttribute("skillInfo",skillInfo);
			model.addAttribute("imgList",imgList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "manager/skillSpaceUser/skillSpaceDetail";
	}
	
	/**
	 * 技能空间审核     郭云鹏 2017-2-27 v2
	 * @param request 
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/skillSpaceDetailV2")
	public String skillSpaceDetailV2(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		try {
			Map<String,Object> baseInfo = skillUserManagerService.getSkillBaseInfo(paramsMap);
			model.addAttribute("baseInfo", baseInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "manager/skillSpaceUser/skillSpaceDetailV2";
	}
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：设置推荐或取消推荐
	 * 创建人： ln
	 * 创建时间： 2016年10月13日
	 * 标记：
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/skillSpaceRecommend")
	public @ResponseBody Map skillSpaceRecommend(HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			boolean flag = skillUserManagerService.updateSkillSpaceRecommend(paramsMap);
			map.put("flag", flag);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：设置个人空间打开或关闭
	 * 创建人： ln
	 * 创建时间： 2016年10月13日
	 * 标记：
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/skillSpaceCloseOrOpen")
	public @ResponseBody Map skillSpaceCloseOrOpen(HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			boolean flag = skillUserManagerService.skillSpaceCloseOrOpen(paramsMap);
			map.put("flag", flag);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：个人空间审核
	 * 创建人： ln
	 * 创建时间： 2016年10月13日
	 * 标记：manager
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/skillSpaceCheck")
	public  String skillSpaceCheck(HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		try {
			String auditState = paramsMap.get("auditState").toString();
			boolean flag = skillUserManagerService.skillSpaceCheck(paramsMap);
			
			if(flag){
				Map<String,Object> baseInfo_map = skillUserManagerService.getSkillBaseInfo(paramsMap);
				if(auditState.equals("1")){
					baseInfo_map.put("auditType", "审核成功");
				}else{
					baseInfo_map.put("auditType", "审核失败");
				}
				//发送审核信息
				sendMessage.sendAuditSuccessMessage(baseInfo_map);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/skillUserManager/skillSpaceList.html";
	}
	
	

	/**
	 * 导出到excel
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/exportToExcel")
	public void exportToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			
			createParameterMap(request);
			
			ReadWriteExcelUtil exportToExcel = skillUserManagerService.exportToExcel(paramsMap);
			//重置输出流，该代码可以加，如果不加，要保证resposne缓冲区中没有其他的数据，但是建议加上
			response.reset();
			OutputStream os = response.getOutputStream();
			//文件下载（添加的配置）
			response.setContentType("application/vnd.ms-excel");
			String filename = "（"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"）";
			filename = new String(filename.getBytes("gbk"),"iso-8859-1");
			response.setHeader("Content-disposition", "attachment;filename="+filename+".xls");
			response.setBufferSize(1024);
			exportToExcel.expordExcel(os);
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：配置资源空间所属分类回显
	 * 创建人： dxf
	 * 创建时间： 2016年2月16日
	 * 标记：
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/toEditLabel")
	public String toEditLabel(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		try {
			List<Map<String, Object>> Labelist = skillUserManagerService.toEditLabel(paramsMap);//查询所有标签
			List<Map<String, Object>> DicSkillist = skillUserManagerService.querySkilDicdata(paramsMap);//查询字典资源中间表
			model.addAttribute("Labelist", Labelist);
			model.addAttribute("DicSkillist", DicSkillist);
			model.addAttribute("map",paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "manager/skillSpaceUser/toEditLabel";
	}
	
	/**
	 * 
	 * 项目名称：dlws-xiaoka-xydk
	 * 描述：执行修改资源空间所属分类
	 * 创建人： dxf
	 * 创建时间： 2016年2月16日
	 * 标记：
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/updateLabel")
	public String updateLabel(HttpServletRequest request, HttpServletResponse response,Model model) {
		createParameterMap(request);
		boolean flag=false;
		try {
			//List<Map<String, Object>> skilList = skillUserManagerService.queryExit(paramsMap);
			flag = skillUserManagerService.updateLabel(paramsMap);//修改所属标签
			
			if(flag==true){
				
				return "redirect:/skillUserManager/skillSpaceList.html";
			}else{
				model.addAttribute("msg","保存失败");
				return "/error";
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg","保存失败");
			return "/error";
			
		}
	}
	
	
	
	
}
